package com.healthdata.controller;

import com.healthdata.entity.User;
import com.healthdata.entity.UserApplication;
import com.healthdata.service.UserService;
import com.healthdata.util.JwtUtil;
import com.healthdata.vo.UserApplicationVO;
import com.healthdata.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasAuthority('ADMIN')") // 修改为hasAuthority
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;
    // 获取所有反馈给管理员的申请列表
    @GetMapping("/applications")
    public List<UserApplicationVO> getAllApplications() {
        return userService.getAllAdminApplications();
    }

    // 处理申请
    @PostMapping("/handleApplication")
    public Map<String, Object> handleApplication(@RequestBody Map<String, Object> handleInfo) {
        Map<String, Object> result = new HashMap<>();
        if (handleInfo.get("applicationId") == null || handleInfo.get("isApproved") == null ) {
            result.put("success", false);
            result.put("message", "缺少必要参数，请提供申请ID、审批结果");
            return result;
        }
        Long applicationId = Long.valueOf(handleInfo.get("applicationId").toString());
        boolean isApproved = (boolean) handleInfo.get("isApproved");
        String adminReply = (String) handleInfo.get("adminReply");

        UserApplication application = userService.getApplicationById(applicationId);
        if (application == null) {
            result.put("success", false);
            result.put("message", "未找到该申请，请确认申请ID是否正确");
        } else if (!"ADMIN".equals(application.getTargetRole())) {
            result.put("success", false);
            result.put("message", "该申请不是反馈给管理员的申请，无法处理");
        } else if (!application.getStatus().startsWith("未处理")) {
            result.put("success", false);
            result.put("message", "该申请已处理，请勿重复操作");
        } else {
            application.setHandleTime(new Date());
            if (isApproved) {
                application.setStatus("已处理");
                application.setAdminReply(adminReply);
            } else {
                application.setStatus("拒绝");
                application.setAdminReply(adminReply);
            }
            boolean success = userService.updateApplication(application);
            result.put("success", success);
            result.put("message", success ? "申请处理成功" : "申请处理失败，请稍后重试");
        }
        return result;
    }
}